package com.xwdeshj.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xwdeshj.dal.Dal_XwCustom;
import com.xwdeshj.entity.XwCustom;
import com.xwdeshj.entity.XwCustomShop;
import com.xwdeshj.entity.XwUserinfo;
import com.xwdeshj.repository.*;
import com.xwdeshj.service.XwCustomService;
import com.xwdeshj.utils.DateUtil;
import com.xwdeshj.utils.helper;
import lombok.extern.slf4j.Slf4j;
import org.n3r.idworker.Sid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.sql.RowSet;
import java.util.Date;

/**
 * Created by BKWJA on 2019/1/13.
 * 定制游
 */
@Slf4j
@Service("xwCustomService")
public class XwCustomServiceImpl implements XwCustomService {

    Logger logger = LoggerFactory.getLogger(XwCustomServiceImpl.class);

    @Autowired
    private XwCustomRepository xwCustomRepository;
    @Autowired
    private XwUserinfoRepository xwUserinfoRepository;
    @Autowired
    private XwCustomShopRepository xwCustomShopRepository;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private Sid sid;

    Dal_XwCustom dal_xwCustom = new Dal_XwCustom();

    /**
     *  1、若是前台项目提交的定制申请，则判断该用户是否已经登录，登录才可以提交申请，并验证用户是否存在
     *  2、后台管理系统，根据手机号码和用户名去查找改用户是否存在
     *  3、匹配农家（景区）字段：目的地，出发地，游玩类型，是否门票
     *  @param custjson :参数值，json格式
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    public JSONObject addcustom(String custjson,HttpServletRequest request) {
        JSONObject result = new JSONObject();

        String uid = helper.ReadCookieMap(request,"uid").toString();//读取当前操作人用户id
        String u_encryptid = helper.ReadCookieMap(request,"uid_encryptid").toString();//读取当前操作人用户加密id
        if((!"".equals(uid) && uid != null) && (!"".equals(u_encryptid) && u_encryptid != null)){
            JSONObject object = new JSONObject();
            //该json数据，每一个必须都要有，否则保存。
            String temp = custjson;
            try {

                custjson=custjson.replace("&quot;", "\"");
                object = JSONObject.parseObject(custjson);
                String user_encryptId = object.getString("user_encryptId");//定制信息的用户加密id
                String type = object.getString("type");//定制类型，1：挑选农家，2：挑选景区
                String category = object.getString("category");//定制类型 1：私人定制，2：团队定制
                String days = object.getString("days");//游玩天数（1天0晚，1天1晚，2天1晚，2天2晚，3天2晚，4天以上）
                String roomtype = object.getString("roomtype"); //住宿类型(0：不住宿，1：经济型，2：豪华型)
                String diningl = object.getString("diningl"); //用餐标准(0：自行安排，5:3-5人桌，8:5-8人桌，10:10-12人桌)
                String playTotalNum = object.getString("playTotalNum"); //游玩总人数
                String palyChildNum = object.getString("palyChildNum"); //游玩儿童人数
                String palyOldNum = object.getString("palyOldNum"); //游玩老人人数
                String min_pricebudgetS = object.getString("min_pricebudget"); //最小_人均预算
                String max_pricebudgetS = object.getString("max_pricebudget"); //最大_人均预算
                String departure = object.getString("departure"); //出发地点
                String destination = object.getString("destination"); //目的地，多个地区使用 ， 进行分隔
                String Wizard = object.getString("Wizard"); //向导需求(0：自行安排，1：领队，2：导游)
                String ticket = object.getString("ticket"); // 门票（1：需要，0：不需要）
                String departuretime = object.getString("departuretime"); //游玩时间
                String palydesc = object.getString("palydesc"); //游玩类型文字说明
                String playType_encryptId = object.getString("playType_encryptId"); //游玩类型加密id，多个id使用 ， 进行分隔
                String otherdemand = object.getString("otherdemand"); //其他需求
                String username = object.getString("username"); //用户名
                String user_tel = object.getString("user_tel"); //联系电话
                String useremail = object.getString("useremail"); //邮箱
                String dataSources = object.getString("dataSources"); //数据来源（0：后台管理系统，1：前端官网）

                //因数据库存储类型为int型，若传递为“”，则为 0
                if("".equals(playTotalNum)){
                    playTotalNum = "0";
                }
                if("".equals(palyChildNum)){
                    palyChildNum = "0";
                }
                if("".equals(palyOldNum)){
                    palyOldNum = "0";
                }

                double min_pricebudget = 0.0;
                if("".equals(min_pricebudgetS)){
                    min_pricebudget = 0.0;
                }else if(!"".equals(min_pricebudgetS)){
                    min_pricebudget = Double.parseDouble(min_pricebudgetS);
                }
                double max_pricebudget = 0.0;
                if("".equals(max_pricebudgetS)){
                    max_pricebudget = 0.0;
                }else if(!"".equals(max_pricebudgetS)){
                    max_pricebudget = Double.parseDouble(max_pricebudgetS);
                }
                //查找该用户是否存在
                XwUserinfo userinfo = xwUserinfoRepository.findByUserEncryptid(user_encryptId);
                if(userinfo != null){

                    String customEncryptid = sid.nextShort();
                    XwCustom xwCustom = new XwCustom();
                    xwCustom.setCustEncryptid(customEncryptid);
                    xwCustom.setApplicantEncryptid(u_encryptid);
                    xwCustom.setApplicantId(uid);
                    xwCustom.setDatasources(dataSources);
                    xwCustom.setCustType(type);
                    xwCustom.setCustCategory(category);
                    xwCustom.setCustDays(days);
                    xwCustom.setCustLivetype(roomtype);
                    xwCustom.setCustDiningl(diningl);
                    xwCustom.setCustPlaytotalnum(Integer.parseInt(playTotalNum));
                    xwCustom.setCustPalychildnum(Integer.parseInt(palyChildNum));
                    xwCustom.setCustPalyoldnum(Integer.parseInt(palyOldNum));
                    //人均预算范围
                    String pricebudget = min_pricebudgetS+"-"+max_pricebudgetS;
                    xwCustom.setCustPerBudget(pricebudget); //记录人均预算范围
                    xwCustom.setCustDeparture(departure);
                    xwCustom.setCustDestination(destination); //多个目的地
                    xwCustom.setCustWizard(Wizard);
                    xwCustom.setCustTicket(ticket);
                    xwCustom.setCustDepartureTime(DateUtil.StringToDate(departuretime,"yyyy-MM-dd"));
                    xwCustom.setCustPaly(palydesc);
                    xwCustom.setPlaytypeEncryptid(playType_encryptId);
                    xwCustom.setCustOther(otherdemand);
                    xwCustom.setCustUserMail(useremail);
                    xwCustom.setCustUserTel(user_tel);
                    xwCustom.setCustUserName(username);
                    xwCustom.setCustCustomTime(new Date());
                    xwCustom.setUserEncryptid(user_encryptId);


                    try {
                        JSONObject jsonObject = new JSONObject();
                        String name = "";
                        if("1".equals(type)){
                            //获取匹配的农家乐店铺加密id
                            name = "农家乐";
                            jsonObject = dal_xwCustom.getfarm_encryptId(min_pricebudget,max_pricebudget,playType_encryptId,palydesc,destination, otherdemand,jdbcTemplate);
                        }else if("2".equals(type)){
                            //挑选景区
                            name = "景区";
                            jsonObject = dal_xwCustom.getsceinc_encryptId(min_pricebudget,max_pricebudget,ticket,playType_encryptId,destination,otherdemand,jdbcTemplate);
                        }


                        String shop_encryptId = "";//匹配的店铺加密id
                        String companyName = ""; //匹配店铺名称
                        JSONArray shopArray = jsonObject.getJSONArray("shoplist");
                        logger.info("匹配记录——"+shopArray.toString());
                        for (int i = 0; i < shopArray.size(); i++) {
                            //将匹配的记录填写到匹配店铺信息表中
                            XwCustomShop xwCustomShop = new XwCustomShop();
                            xwCustomShop.setCustEncryptid(customEncryptid);
                            xwCustomShop.setUserEncryptid(user_encryptId);
                            xwCustomShop.setCustType(type);
                            xwCustomShop.setShopEncryptid((String) shopArray.getJSONObject(i).get("shop_encryptId"));
                            xwCustomShop.setShopCompanyname((String) shopArray.getJSONObject(i).get("CompanyName"));
                            xwCustomShopRepository.save(xwCustomShop);

                            if (i == 0) {
                                shop_encryptId = (String) shopArray.getJSONObject(i).get("shop_encryptId");
                                companyName = (String) shopArray.getJSONObject(i).get("CompanyName");
                            } else {
                                shop_encryptId += "," + (String) shopArray.getJSONObject(i).get("shop_encryptId");
                                companyName += "," + (String) shopArray.getJSONObject(i).get("CompanyName");
                            }
                        }
                        if(!shop_encryptId.equals("")){
                            //匹配到记录才存入数据库中
                            logger.info("当前操作人uid加密id："+u_encryptid+"---匹配"+name+"店铺名称："+companyName);
                            xwCustom.setCustShopEncryptid(shop_encryptId); //数据无法删除
                            xwCustom.setCustShopCompanyname(companyName); //数据无法删除
                            xwCustomRepository.save(xwCustom);
                            logger.info("当前操作人uid加密id："+u_encryptid+"---数据保存成功");

                            result.put("cust_Encryptid",customEncryptid);//定制游加密id
                            result.put("user_Encryptid",user_encryptId); //用户加密id
                            result.put("user_id",userinfo.getUserId()); //用户名id
                            result.put("tel",userinfo.getUserTel()); //用户电话号码
                            result.put("status",0);
                            result.put("msg","ok");
                        }else {
                            //未配置，无法存入数据库
                            result.put("status",40004);
                            result.put("msg","未能为你挑选到合适的农家或景区,降低要求就能够找到满意的农家或景区");
                        }

                    }catch (Exception e){
                        e.printStackTrace();
                        System.out.println("数据保存失败！");
                        result.put("status",40002);
                        result.put("msg",e);
                    }
                }else {
                    result.put("status",40003);
                    result.put("msg","该用户不存在，请选择有效的用户！");
                }
            } catch (Exception e) {
                e.printStackTrace();
                result.put("status",40002);
                result.put("msg","序列化失败");
            }
        }else {
            result.put("status",40001);
            result.put("msg","uid不能为空，请先登录后再操作！");
        }
        System.out.println("addcustom:"+result.toString());
        return result;
    }


    //获取当前定制的一条信息
    @Override
    public JSONObject getcustominfo(String user_Encryptid, String cust_Encryptid, HttpServletRequest request) {
        JSONObject result = new JSONObject();
        String uid_encryptid = helper.ReadCookieMap(request,"uid_encryptid").toString();
        String uid = helper.ReadCookieMap(request,"uid").toString();
        if(!"".equals(uid_encryptid) && !"".equals(uid)){
            if(!user_Encryptid.equals("") && !cust_Encryptid.equals("")){
                result = dal_xwCustom.getcustominfo(user_Encryptid,cust_Encryptid,jdbcTemplate);
            }else {
                result.put("status",40002);
                result.put("msg","user_Encryptid,cust_Encryptid不能为空！");
            }
        }else {
            result.put("status",40001);
            result.put("msg","uid不能为空,请先登录！");
        }
        System.out.println("getcustomlist:"+result.toString());
        return result;
    }


    //获取定制游列表
    @Override
    public JSONObject getcustolist(Integer pageindex, Integer pagesize, String starttime, String endtime,
                                   String sortfild, String sortway, String type, String category,
                                   String datasource, String applicant,String searchval,String searchkey,
                                  String user_encryptId,HttpServletRequest request) {
        JSONObject result = new JSONObject();

        result = dal_xwCustom.getcustolist(pageindex,pagesize,starttime,endtime,sortfild,sortway,type,
                category,datasource,applicant,searchval,searchkey,user_encryptId,jdbcTemplate);

        System.out.println("getcustolist:"+result.toString());
        return result;
    }

    //删除
    @Override
    @Modifying
    @Transactional(rollbackFor = Exception.class)
    public JSONObject delcustom(String cust_Encryptid, HttpServletRequest request) {
        JSONObject result = new JSONObject();
        String uid_encryptid = helper.ReadCookieMap(request,"uid_encryptid").toString();
        String uid = helper.ReadCookieMap(request,"uid").toString();
        if(!"".equals(uid_encryptid) && !"".equals(uid)){
            if(!cust_Encryptid.equals("")){

                if(cust_Encryptid.indexOf(",") == -1){
                    //单个删除
                    int flag = 0;

                    XwCustom xwCustom = new XwCustom();
                    xwCustom.setCustEncryptid(cust_Encryptid);
                    boolean Customtemp = xwCustomRepository.exists(Example.of(xwCustom));
                    if(Customtemp){
                        XwCustomShop xwCustomShop = new XwCustomShop();
                        xwCustomShop.setCustEncryptid(cust_Encryptid);
                        boolean temp = xwCustomShopRepository.exists(Example.of(xwCustomShop));
                        if(temp){
                            xwCustomShopRepository.deleteByCustEncryptid(cust_Encryptid);
                        }
                        flag =  xwCustomRepository.deleteByCustEncryptid(cust_Encryptid);
                    }
                    if(flag == 1){
                        result.put("status",0);
                        result.put("msg","ok");
                    }else {
                        result.put("status",500);
                        result.put("msg","删除失败！");
                    }
                }else {
                    //批量删除
                    int flag = 0;
                    String[] tids = cust_Encryptid.split(",");
                    for (int i = 0; i < tids.length; i++) {
                        XwCustom xwCustom = new XwCustom();
                        xwCustom.setCustEncryptid(tids[i]);
                        boolean Customtemp = xwCustomRepository.exists(Example.of(xwCustom));
                        if(Customtemp){
                            XwCustomShop xwCustomShop = new XwCustomShop();
                            xwCustomShop.setCustEncryptid(cust_Encryptid);
                            boolean temp = xwCustomShopRepository.exists(Example.of(xwCustomShop));
                            if(temp){
                                xwCustomShopRepository.deleteByCustEncryptid(tids[i]);
                            }
                            flag = xwCustomRepository.deleteByCustEncryptid(tids[i]);
                        }

                    }
                    if(flag == 1){
                        result.put("status",0);
                        result.put("msg","ok");
                    }else {
                        result.put("status",500);
                        result.put("msg","删除失败！");
                    }
                }

            }else {
                result.put("status",5000);
                result.put("msg","cust_Encryptid不能为空！");
            }
        }else {
            result.put("status",40001);
            result.put("msg","uid不能为空,请先登录！");
        }
        System.out.println("delcustom:"+result.toString());
        return result;
    }

    /**
     * 获取某一次的匹配店铺详细信息
     */
    @Override
    public JSONObject getcustomAnduserlist(Integer pageindex,Integer pagesize,String sortfild,String sortway,
                                               String user_encryptId,String cust_encryptId,String shoptype,
                                               String business_type,String cust_type,HttpServletRequest request) {
        JSONObject result = new JSONObject();
        String uid_encryptid = helper.ReadCookieMap(request,"uid_encryptid").toString();
        String uid = helper.ReadCookieMap(request,"uid").toString();
        if(!"".equals(uid_encryptid) && !"".equals(uid)){

            if(!user_encryptId.equals("") && !cust_type.equals("") && !cust_encryptId.equals("")){

                if(cust_type.equals("1")){
                    //农家
                    result = dal_xwCustom.getcustomfarmAnduserlist(pageindex,pagesize,sortfild,sortway,user_encryptId,
                            cust_encryptId,shoptype,business_type,jdbcTemplate);

                }else if(cust_type.equals("2")){
                    //景区
                    result = dal_xwCustom.getcustomScenicAnduserlist(pageindex,pagesize,sortfild,sortway,user_encryptId,
                            cust_encryptId,shoptype,business_type,jdbcTemplate);
                }

            }else {
                result.put("status",5000);
                result.put("msg","user_encryptId,cust_encryptId,cust_type不能为空！");
            }

        }else {
            result.put("status",40001);
            result.put("msg","uid不能为空,请先登录！");
        }
        System.out.println("getcustomAnduserlist:"+result.toString());
        return result;
    }


}
